<template>
  <NoTabBarPage
    :scroll-props="{ onPulldown, height: '100%' }"
    custom-class="detail-and-record"
  >
    <div class="detail-and-record__wrapped">
      <div class="detail-and-record__header">
        <div class="detail-and-record__header-count">
          <image src="@/assets/jifen/icon-corn-middle.png" class="icon" />
          <span class="count">{{ points }}</span>
          <span class="label">积分</span>
        </div>
        <div class="detail-and-record__header-tip">
          积分可以在积分商城兑换礼品
        </div>
      </div>

      <div class="detail-and-record__chart">
        <div class="detail-and-record__chart-wrapped">
          <div class="detail-and-record__chart-wrapped_label">积分增长曲线</div>
          <canvas
            id="mychart-bar"
            canvas-id="mychart-bar"
            class="line-canvas"
          ></canvas>
        </div>
      </div>

      <div class="detail-and-record__content">
        <div class="detail-and-record__content-panel">
          <div class="panel-tabs">
            <div
              v-for="(item, index) in tabsOptions"
              :key="item.value"
              :class="[
                'panel-tabs__item',
                tabActive === item.value && 'is-active',
                index === 0 ? 'first' : 'end',
              ]"
              @tap="onTabActive(item.value)"
            >
              <span class="panel-tabs__item-label">{{ item.label }}</span>
              <span
                v-show="tabActive === item.value"
                class="panel-tabs__item-line"
              ></span>
            </div>
          </div>
          <div class="panel-content">
            <JifenDetail v-if="tabActive === 1" :data="selfList" />
            <ExchangeRecord v-else :data="exchangeList" />
          </div>
        </div>
      </div>
    </div>
  </NoTabBarPage>
</template>

<script setup lang="ts">
// import * as echarts from "@/components/common-chart/echarts";
import uCharts from "@/components/ucharts/u-charts";
import NoTabBarPage from "@/components/common-page/noTabBar-page.vue";
// import CommonChart from "@/components/common-chart/index.vue";
import JifenDetail from "./components/jifen-detail.vue";
import ExchangeRecord from "./components/exchange-record.vue";
import "./index.less";
import { ref } from "vue";
import Taro, { useLoad } from "@tarojs/taro";
import {
  apiQueryPointsExchangeList,
  apiQueryPointsHistory,
  apiQuerySelfPoints,
  apiQueryselfPointsList,
} from "@/apis/jifen";
import {
  IExchangeItemRes,
  IPointsHistoryItem,
  ISelfPointListItemRes,
} from "@/apis/types/jifen";
import { ResponseCodeEnum } from "@/constants/index";
defineOptions({
  name: "detail-and-record",
});

const tabsOptions = [
  { label: "积分明细", value: 1 },
  { label: "兑换记录", value: 2 },
];

const points = ref(0);
const tabActive = ref(2);
const selfList = ref<ISelfPointListItemRes[]>([]);
const exchangeList = ref<IExchangeItemRes[]>([]);
const pagination = ref({ page: 1, pageSize: 20 });
let chart: any = null;

useLoad((params) => {
  const { type } = params;
  tabActive.value = parseInt(type || 1);

  queryPointsList();
  queryExchangeList();
  querySelfPointsServer();
  queryPointHistoryServer();
});

const onPulldown = async (done: Function) => {
  try {
    await queryPointsList();
    await queryExchangeList();
    await querySelfPointsServer();
    await queryPointHistoryServer();
  } catch (error) {
  } finally {
    done();
  }
};

const init = (aXisxData: string[], seriesData: number[]) => {
  const query = Taro.createSelectorQuery();

  query
    .select("#mychart-bar")
    .fields({ node: true, size: true })
    .exec((res) => {
      // const canvasDpr = Taro.getSystemInfoSync().pixelRatio;
      const canvasWidth = res[0].width;
      const canvasHeight = res[0].height;
      const ctx = Taro.createCanvasContext("mychart-bar");
      // console.log(canvasDpr, canvasWidth, canvasHeight);
      chart = new uCharts({
        type: "line",
        context: ctx,
        width: canvasWidth,
        height: canvasHeight,
        categories: aXisxData,
        series: [
          {
            name: "积分",
            data: seriesData,
          },
        ],
        pixelRatio: 1,
        animation: true,
        background: "#FFFFFF",
        color: ["#6CCDBA"],
        padding: [15, 20, 0, 20],
        enableScroll: false,
        legend: {},
        xAxis: {
          disableGrid: true,
          // rotateLabel: true,
          labelCount: 5,
        },
        yAxis: {
          disabled: true,
          gridType: "dash",
          dashLength: 2,
        },
        extra: {
          line: {
            type: "straight",
            width: 2,
            activeType: "hollow",
          },
        },
      });
    });
};

const onTabActive = (value: number) => {
  if (tabActive.value != value) {
    tabActive.value = value;
  }
};

const onLineChartOptions = (data: IPointsHistoryItem[]) => {
  const xAxisData = data.map((item) => item.date);
  const seriesData = data.map((item) => item.points);

  init(xAxisData, seriesData);
};
const queryPointsList = () => {
  apiQueryselfPointsList(pagination.value).then((res: any) => {
    const { code, data } = res;
    if (code === ResponseCodeEnum.SUCCESS) {
      selfList.value = data.items || [];
    }
  });
};

const queryExchangeList = () => {
  apiQueryPointsExchangeList(pagination.value).then((res: any) => {
    const { code, data } = res;
    if (code === ResponseCodeEnum.SUCCESS) {
      exchangeList.value = data.items || [];
    }
  });
};

const querySelfPointsServer = () => {
  apiQuerySelfPoints().then((res: any) => {
    const { code, data } = res;
    if (code === ResponseCodeEnum.SUCCESS) {
      points.value = data.value;
    }
  });
};

const queryPointHistoryServer = () => {
  apiQueryPointsHistory().then((res: any) => {
    const { code, data } = res;
    if (code === ResponseCodeEnum.SUCCESS) {
      onLineChartOptions(data.history);
    }
  });
};
</script>

<style lang="less">
.detail-and-recor {
  .line-canvas {
    width: 100%;
    height: 300px;
  }
}
</style>
